package com.flea.web.listener;

import com.flea.model.User;
import com.flea.util.SessionUtils;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;

@WebListener
@Slf4j
public class UserSessionListener implements HttpSessionAttributeListener {

    public void attributeAdded(HttpSessionBindingEvent event) {
        User user = SessionUtils.getSessionUser(event.getSession());
        if (user == null) {
            return;
        }
        log.info("==={} 上线了", user.getLogin());
        SessionUtils.addUserHttpSession(user.getId(), event.getSession().getId());
    }

    public void attributeRemoved(HttpSessionBindingEvent event) {
        User user = SessionUtils.getSessionUser(event.getSession());
        if (user == null) {
            return;
        }
        log.info("==={} 下线了", user.getLogin());
        SessionUtils.removeUserHttpSession(user.getId());
    }

}
